package code5;

import java.io.*;
import java.net.Socket;

public class ClientReceiveFile extends Thread {

    private String str = null;

    public ClientReceiveFile(String str){this.str=str;}

    @Override
    public void run(){

        DataInputStream dis = null;
        DataOutputStream dos = null;
        try {
            Socket s = new Socket("127.0.0.1", 1239);
            System.out.println("客户端已连接服务器，准备接收文件！");

            // 对服务器发送的信息进行解析，得到文件名称
            String[] s1 = str.split(" ");
            String[] s2 = s1[1].split("/");
            String fileName = s2[s2.length-1];

            // 要准备客户端接收文件的文件夹
            File file = new File("F:/ClientReceivedFile/"+fileName);

            dis = new DataInputStream(s.getInputStream());
            dos = new DataOutputStream(new FileOutputStream(file));

            byte[] barr = new byte[1024];
            int res = 0;
            while((res=dis.read(barr))!=-1){
                dos.write(barr,0,res);
                dos.flush();
            }
            System.out.println("文件"+fileName+"接收成功！");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(null!=dos){
                try {
                    dos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null!=dis){
                try {
                    dis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
